
//
//  ZYYTopic.m
//  bookTableView
//
//  Created by zhaoyunyi on 15-1-3.
//
//

#import "DZYTopic.h"
@implementation DZYTopic
@synthesize DZYdelegate;
//- (id)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        self.frame = frame;
//        [self setSelf];
//    }
//    return self;
//}
-(void)setSelf{
    self.pagingEnabled = YES;
    self.scrollEnabled = YES;
    self.delegate = self;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.backgroundColor = [UIColor redColor];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    [self setSelf];
    self.anchorViewWidth=[self.superview viewWithTag:4].frame.size.width;
    self.anchorViewHeight=[self.superview viewWithTag:4].frame.size.height;
    NSLog(@"%f--%f",self.anchorViewWidth,self.anchorViewHeight);
    
    // Drawing code
    //[self upDate];
}
-(void)upDate
{
    //直接传过来的NSMutableArray 会少掉第一个和最后一个，所以传递NSArry，中间temp
    NSMutableArray * tempImageArray = [[NSMutableArray alloc]init];
    
       for (id obj in self.pics) {
        [tempImageArray addObject:obj];
    }
    self.pics = Nil;
    self.pics = tempImageArray;
    
    //遍历每个数组并进行操作
    int i = 0;
    for (id obj in self.pics) {
        pic= Nil;
        pic = [[UIButton alloc] init];
        pic.imageView.contentMode = UIViewContentModeScaleAspectFill;
//        pic.imageView.contentMode =
//        UIViewContentModeScaleAspectFill;
        [pic.imageView setClipsToBounds:YES];
        [pic setFrame:CGRectMake(i*self.frame.size.width,0, self.frame.size.width, self.frame.size.height)];
        NSLog(@"button Width:%f",pic.frame.size.width);
        UIImageView * tempImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        //设置imageview的图片填充模式
        tempImage.contentMode =
        UIViewContentModeScaleAspectFill;
//        tempImage.contentMode =
//        UIViewContentModeScaleAspectFill;
        [tempImage setClipsToBounds:YES];
        
        if ([[obj objectForKey:@"isLoc"]boolValue]) {
            [tempImage setImage:[obj objectForKey:@"pic"]];
        }else{
            if ([obj objectForKey:@"placeholderImage"]) {
                [tempImage setImage:[obj objectForKey:@"placeholderImage"]];
            }
            [NSURLConnection sendAsynchronousRequest:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[obj objectForKey:@"pic"]]]
                                               queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                                   if (!error && responseCode == 200) {
                                                       tempImage.image = Nil;
                                                       UIImage *_img = [[UIImage alloc] initWithData:data];
                                                       [tempImage setImage:_img];
                                                   }else{
                                                       if ([obj objectForKey:@"placeholderImage"]) {
                                                           [tempImage setImage:[obj objectForKey:@"placeholderImage"]];
                                                       }
                                                   }
                                               }];
        }
       
        [pic addSubview:tempImage];
        [pic setBackgroundColor:[UIColor grayColor]];
        pic.tag = i;
        [pic addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        NSLog(@"WIDTH---%f",self.frame.size.width);
        NSLog(@"height---%f",tempImage.frame.size.height);
        [self addSubview:pic];
        
//        UILabel * title = [[UILabel alloc]initWithFrame:CGRectMake(i*self.frame.size.width, self.frame.size.height-30, self.frame.size.width,30)];
//        [title setBackgroundColor:[UIColor blackColor]];
//        //        [title sette
//        [title setAlpha:.7f];
//        [title setText:[NSString stringWithFormat:@" %@",[obj objectForKey:@"title"]]];
//        [title setTextColor:[UIColor whiteColor]];
//        [title setFont:[UIFont fontWithName:@"Helvetica" size:12]];
//        //[self addSubview:title];
        i++;
    }
    [self setContentSize:CGSizeMake(self.frame.size.width*[self.pics count], self.frame.size.height)];
    
    NSLog(@"-----%f",self.frame.size.width);
    [self setContentOffset:CGPointMake(0, 0) animated:NO];
    
    if (scrollTimer) {
        [scrollTimer invalidate];
        scrollTimer = nil;
        
    }

    if ([self.pics count]>1) {
        scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTopic) userInfo:nil repeats:YES];
    }
//    UIButton *a = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
//    [a setBackgroundColor:[UIColor redColor]];
//    [self addSubview:a];
}
-(void)click:(id)sender{
    [DZYdelegate didClick:[sender tag]];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat Width=self.frame.size.width;
    if (scrollView.contentOffset.x == self.frame.size.width) {
        flag = YES;
    }
    if (flag) {
        if (scrollView.contentOffset.x <= 0) {
            [self setContentOffset:CGPointMake(Width*([self.pics count]), 0) animated:NO];
        }else if (scrollView.contentOffset.x >= Width*([self.pics count])) {
            [self setContentOffset:CGPointMake(0, 0) animated:NO];
        }
        flag = NO;
    }
    float a = self.contentOffset.x;
    float b = self.frame.size.width;
    currentPage = scrollView.contentOffset.x/self.frame.size.width;
    [DZYdelegate currentPage:currentPage total:[self.pics count]];
    scrollTopicFlag = currentPage;
}
-(void)scrollTopic{
    
    
    if (scrollTopicFlag >= [self.pics count]-1) {
        scrollTopicFlag = 0;
    }else {
        scrollTopicFlag++;
    }
    if(scrollTopicFlag == 0)
    {
         [self setContentOffset:CGPointMake(self.frame.size.width*scrollTopicFlag, 0) animated:NO];
    }
    else
    {
          [self setContentOffset:CGPointMake(self.frame.size.width*scrollTopicFlag, 0) animated:YES];
    }
   
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if ([self.pics count]>1) {
        scrollTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(scrollTopic) userInfo:nil repeats:YES];
    }
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollTimer) {
        [scrollTimer invalidate];
        scrollTimer = nil;
    }
    
}
-(void)releaseTimer{
    if (scrollTimer) {
        [scrollTimer invalidate];
        scrollTimer = nil;
        
    }
}

@end
